from pydantic import BaseModel, Field
from typing import List, Dict, Optional, Union, Any


class BasePersonaConfig(BaseModel):
    """基础人格配置"""
    is_based: bool = Field(True, description="是否为基础人格")
    tag: str = Field(..., description="人格代号")
    name: str = Field(..., description="人格名称")
    existing_form: str = Field(..., description="存在形式描述")
    portrait: str = Field(..., description="形象描述")
    character: str = Field(..., description="性格特征")
    talking_style: str = Field(..., description="说话风格")
    greeting: str = Field(..., description="问候语")
    knowledge: str = Field(..., description="专业知识")
    fallback: str = Field(..., description="备用回复")


class ExtendedPersonaConfig(BasePersonaConfig):
    """扩展人格配置（非基础人格）"""
    is_based: bool = Field(False, description="是否为基础人格")
    # 基础人格特有字段
    core_positioning: Optional[Dict[str, Any]] = Field(
        default_factory=dict, 
        description="核心定位信息"
    )
    character_behavior: Optional[Dict[str, Any]] = Field(
        default_factory=dict, 
        description="角色行为特征"
    )
    
    # 非基础人格特有字段
    background_knowledge: Dict[str, Union[str, Any]] = Field(
        default_factory=dict,
        description="背景知识配置"
    )
    function_interaction: Dict[str, Union[str, Any]] = Field(
        default_factory=dict,
        description="功能交互配置"
    )
    expansion_customization: Dict[str, Union[str, Any]] = Field(
        default_factory=dict,
        description="扩展定制配置"
    )
    
    # 覆盖基础字段的默认值
    # core_positioning: Dict[str, str] = Field(
    #     default_factory=dict, 
    #     description="核心定位信息"
    # )
    # character_behavior: Dict[str, str] = Field(
    #     default_factory=dict, 
    #     description="角色行为特征"
    # )

class PersonaConfig(BaseModel):
    """统一人格配置模型"""
    config: Union[BasePersonaConfig, ExtendedPersonaConfig] = Field(
        ..., 
        description="人格配置数据"
    )
    
    @classmethod
    def from_dict(cls, data: dict):
        """根据is_based字段动态创建正确类型"""
        is_based = data.get('is_based', True)
        
        if is_based:
            return cls(config=BasePersonaConfig(**data))
        else:
            return cls(config=ExtendedPersonaConfig(**data))

class ChatRequest(BaseModel):
    session_id: str
    message: str
    persona: Optional[str] = None

class ChatResponse(BaseModel):
    session_id: str
    response: str
    persona: str